package com.solcoo.merchant.ui.setting;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.solcoo.common.util.StringUtil;
import com.solcoo.merchant.ApplicationExt;
import com.solcoo.merchant.Constant;
import com.solcoo.merchant.R;
import com.solcoo.merchant.base.BaseActivity;
import com.solcoo.merchant.base.task.TaskHelper;
import com.solcoo.merchant.base.task.TaskHelper.Callback;
import com.solcoo.merchant.manager.UserManager;
import com.solcoo.merchant.model.User;
import com.solcoo.merchant.util.DialogUtil;
import com.solcoo.merchant.util.ViewUtil;
import com.solcoo.merchant.util.CheckUtil.CheckResult;

public abstract class EditBaseActivity extends BaseActivity {

	public static final String EDIT_KEY = "editKey";

	public static final String EDIT_NAME = "editName";

	public static final String EDIT_BOX = "editBox";

	public static final String EDIT_OLD_VALUE = "editOldValue";

	private Dialog successDialog;

	protected String oldValue;

	protected String editKey;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		successDialog = DialogUtil.createDialog(this, successOnClickListener,
				null, null, "修改成功", null);
		oldValue = StringUtil.defaultIfBlank(getIntent().getStringExtra(
				EDIT_OLD_VALUE));
		editKey = getIntent().getStringExtra(EDIT_KEY);
	}

	@Override
	protected void onResume() {
		super.onResume();
		TextView editName = (TextView) findViewById(R.id.edit_name);
		editName.setText(getIntent().getStringExtra(EDIT_NAME) + ":");
	}

	public void saveOnClick(View v) {
		CheckResult mCheckResult = checkValue();
		if (mCheckResult.isSuccess()) {
			TaskHelper.oper(
					v.getContext(),
					Constant.URL.getEdit(editKey, getValue(),
							ApplicationExt.getUser().yonghum), editCallback,
					User.class);
		} else {
			ViewUtil.showToast(this, getIntent().getStringExtra(EDIT_NAME)
					+ mCheckResult.failMsg);
		}
	}

	private Callback<User> editCallback = new Callback<User>() {

		@Override
		public void onSuccess(User result) {
			UserManager.getInstance().setUser(result);
			successDialog.show();
		}

		@Override
		public void onFail(User result) {
			ViewUtil.showToast(EditBaseActivity.this, result.failMsg);
		}
	};

	private DialogInterface.OnClickListener successOnClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
		}
	};

	protected abstract String getValue();

	protected abstract CheckResult checkValue();

}
